/*  ----------------------------------------------------------------------------
 *  Arello Mobile
 *  Fast 3d Engine
 *  ----------------------------------------------------------------------------
 * Except where otherwise noted, this work is licensed under
 * http://creativecommons.org/licenses/by/3.0
 */

#include <threads/threads.h>
#include <libkern/OSAtomic.h>

#include <mach/mach.h>
#include <mach/mach_time.h>

#include <pthread.h>
#include <unistd.h>

namespace liba
{
namespace threads
{

#ifndef IPHONE_VERSION
int interlocked_increment(counter_type * value)
{
	int result = IncrementAtomic( reinterpret_cast<long *>( value ) );
	return *value;
}

int interlocked_decrement(counter_type * value)
{
	int result = DecrementAtomic( reinterpret_cast<long *>( value ) );
	return *value;
}
#endif

void sleep(int time_ms)
{
	usleep( time_ms * 1000 );
}

__int64_t get_precise_tick_count()
{
	static mach_timebase_info_data_t sTimebaseInfo;
	uint64_t time = mach_absolute_time();
	uint64_t nanos;
	
	// If this is the first time we've run, get the timebase.
	// We can use denom == 0 to indicate that sTimebaseInfo is
	// uninitialised because it makes no sense to have a zero
	// denominator is a fraction.
	if ( sTimebaseInfo.denom == 0 ) {
		(void) mach_timebase_info(&sTimebaseInfo);
	}
	
	// Do the maths.  We hope that the multiplication doesn't
	// overflow; the price you pay for working in fixed point.
	nanos = time * sTimebaseInfo.numer / sTimebaseInfo.denom;
	return ((double)nanos / 1000000.0);
}

double get_precise_tick_time()
{
	return 0.001;
}

} //namespace threads
} //namespace liba

